package com.kingyea.mobilepolice.config.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.util.Assert;

/**
 * 在请求前面写入header信息
 */
public class OAuth2FeignRequestInterceptor4SysClient implements RequestInterceptor {

    private static final String AUTHORIZATION_HEADER = "Authorization";
    private static final String BEARER_TOKEN_TYPE = "Bearer";
    private final Logger LOGGER = LoggerFactory.getLogger(getClass());
    private final OAuth2RestTemplate oAuth2RestTemplate;
    @Value("${kingyea.mobilepolice.security.isEnableSecurity}")
    private Boolean isEnableSecurity;

    @Autowired
    private Oauth2ClientProperties oauth2ClientProperties;


    public OAuth2FeignRequestInterceptor4SysClient(OAuth2RestTemplate oAuth2RestTemplate) {
        Assert.notNull(oAuth2RestTemplate, "Context can not be null");
        this.oAuth2RestTemplate = oAuth2RestTemplate;
    }

    /**
     * 重点方法 feign 的HttpClient必须换成 Okhttp，否则可能失效,认证方必须开启client_credentials
     */
    @Override
    public void apply(RequestTemplate template) {
        if (isEnableSecurity) {
            LOGGER.debug("Constructing Header {} for Token {}", AUTHORIZATION_HEADER, BEARER_TOKEN_TYPE);
            if(template.headers().containsKey("RetryServerToken")){// 自定义token失效重试
                System.out.println(" 旧 Token 失效，置空 OAuth2ClientContext 中的 token对象，重试ing...");
                try {
                    Thread.sleep(2000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                oAuth2RestTemplate.getOAuth2ClientContext().setAccessToken(null);
            }
            System.out.println(" >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ClientId: "+oauth2ClientProperties.getClientId()+" >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> TOKEN: " + oAuth2RestTemplate.getAccessToken().toString());
            template.header(AUTHORIZATION_HEADER,
                    String.format("%s %s",
                            BEARER_TOKEN_TYPE,
                            oAuth2RestTemplate.getAccessToken().toString()));
        }

    }
}